﻿using BaseDao;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AMInstantMessagingServerDao
{
    public class UserProvider : MemoryBaseProvider<UserModel>
    {
        public UserProvider()
        {
            UserName2IdMappingCacheKey = GetCacheKey("HashMap", "UserName2Id");
            UserToken2ClientInfoMappingCacheKey = GetCacheKey("HashMap", "Token2ClientInfo");
        }

        public string UserName2IdMappingCacheKey = null;
        public string UserToken2ClientInfoMappingCacheKey = null;

        /// <summary>
        /// 根据用户名获取Id
        /// </summary>
        /// <param name="user_name"></param>
        /// <returns></returns>
        public long GetUserIdByUserName(string user_name)
        {
            if (!Databse.KeyExists(UserName2IdMappingCacheKey))
                return -1;

            var id_redis = Databse.HashGet(UserName2IdMappingCacheKey, user_name);
            if (id_redis.IsNull)
                return -1;

            return (long)id_redis;
        }

        /// <summary>
        /// 设置小票与客户端信息
        /// </summary>
        /// <param name="info"></param>
        /// <param name="token"></param>
        public void SetClientInfoAndToken(UserClientInfo info, string token)
        {
            Databse.HashSet(UserToken2ClientInfoMappingCacheKey, token, JsonConvert.SerializeObject(info));
        }

        /// <summary>
        /// 获取客户端信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public UserClientInfo GetClientInfoByToken(string token)
        {
            var info_redis = Databse.HashGet(UserToken2ClientInfoMappingCacheKey, token);
            if (info_redis.IsNull)
                return null;

            return JsonConvert.DeserializeObject<UserClientInfo>(info_redis);
        }

        /// <summary>
        /// 根据Token删除客户端信息
        /// </summary>
        /// <param name="user_token"></param>
        /// <returns></returns>
        public bool RemoveClientInfoByToken(string user_token)
        {
            return Databse.HashDelete(UserToken2ClientInfoMappingCacheKey, user_token);
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <param name="user_name"></param>
        /// <returns></returns>
        public UserModel GetUserByUserName(string user_name)
        {
            long id = GetUserIdByUserName(user_name);
            if (id <= 0)
                return null;

            return GetItemById(id);
        }

        /// <summary>
        /// 添加一个用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public override bool Add(UserModel model)
        {
            var status = base.Add(model);
            Databse.HashSet(UserName2IdMappingCacheKey, model.UserName, model.Id);
            return status;
        }
    }
}
